package com.minisoft.ydac;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import com.minisoft.enums.AgentTypeEnum;
import com.minisoft.utils.HttpClientService;
import org.redisson.api.RBucket;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author JueSu
 * @description: TODO
 * @date 2024/4/5 8:39
 */
public class WxbPushData {

    private static boolean isTest = false;
    private static  String client_id = "EqlbKwe41g5GBDWA";
    private static  String client_secret = "qplyotHLJIaRgNxkbBWve64TVuKrwnPA";
    static HttpClientService httpClientService = new HttpClientService();
    private static String HOST = "https://open.wangxiaobao.com";
    static JSONObject wxbProjectMapping = JSONUtil.parseObj("{\"1000112\": 296184550369796096, \"1000114\": 394728526290354176, \"1000125\": 424480260159971328, \"1001242\": 370120403227516928, \"1001267\": 429514760640270336, \"1001269\": 377762305510744064, \"1001270\": 373426142339661824, \"1001272\": 296122905077481472, \"1001278\": 379547486953406464, \"1001284\": 401265608227823616}");
    private static Map<Integer,String> dealDateAttrMap = new HashMap<>();
    static {
        dealDateAttrMap.put(1,"reserveTime");
        dealDateAttrMap.put(2,"subscribeTime");
        dealDateAttrMap.put(3,"signTime");
        if (isTest) {
            client_id = "eHcMNqbFIBraRg1v";
            client_secret = "iRyjpc1QFZW0OPrms8eaH7gAdYMThX4o";
            HOST = "https://open.test.wangxiaobao.com";
            wxbProjectMapping = JSONUtil.parseObj("{\"1000118\": 357340616041955328}");
        }
    }

    public static void visitSyncEs() {
        String esResult = FileUtil.readString(WxbPushData.class.getResource("/esResult.txt"),"utf-8");
        JSONObject esJson = JSONUtil.parseObj(esResult);
        JSONArray hits = esJson.getByPath("result.rawResponse.hits.hits", JSONArray.class);
        List<String> ids = new ArrayList<>();

        Map<String,String> map = getProjectIdMap();
        Map<String, String> headerSignV1 = getHeaderSignV1();
        hits.forEach(item -> {
            JSONObject json = (JSONObject) item;
            List<String> message = json.getByPath("fields.message", List.class);
            String substring = message.get(0).substring(5).replace(",\"errCode\":\"UNKNOWN_CONSULTANTS\",\"errMsg\":\"未知的置业顾问\"","");
            JSONObject jsonObject = JSONUtil.parseObj(substring);
            JSONArray data = jsonObject.getByPath("data.records",JSONArray.class);

            String externalCusId = null;
            for (Object datum : data) {
                JSONObject jsonObject1 = (JSONObject) datum;
                externalCusId = jsonObject1.getStr("externalCusId");
            }
            System.out.println(CollectionUtil.join(ids,","));
            JSONObject params = new JSONObject();
            params.put("estateId",map.get(externalCusId));
            params.put("records",data);
            System.out.println(params);
            String s = httpClientService.doPost(HOST + "/api/ai-voice/v1/visit/sync", params.toString(), headerSignV1);
            System.out.println(s);
        });
    }

    /**
     * 推送单个客情
     * "旺小宝智能工牌新增接访记录结果" and 6289
     */
    public static void visitSync() {
        JSONObject params = JSONUtil.parseObj("{\"estateId\":429514760640270336,\"records\":[{\"externalVisitId\":1140805,\"gender\":2,\"externalCusId\":\"dcf8d8f7cb9048869ccd2cef0ee5a918\",\"customerName\":\"刘女士\",\"consultantName\":\"刘斯元\",\"customerPhone\":\"135****7058\",\"visitTime\":\"2024-12-10 09:41:55\",\"visitCount\":1,\"consultantPhone\":\"13610978000\"}]}");
//        params.put("estateId","429514760640270336");
        String s = httpClientService.doPost(HOST + "/api/ai-voice/v1/visit/sync", params.toString(), getHeaderSignV1());
    }

    public static void visitSyncExcel() {
        ExcelReader staffReader = new ExcelReader("D:\\\\旺小宝同步到访\\250330.xlsx", 0);
        List<Map<String, Object>> list = staffReader.readAll();
        //把电话脱敏和顾问手机号转成字符串
        list.forEach(item -> {
            String customerPhone = item.get("customerPhone").toString();
            item.put("customerPhone",DesensitizedUtil.mobilePhone(customerPhone));
            String consultantPhone = item.get("consultantPhone").toString();
            item.put("consultantPhone",consultantPhone);
            //visitTime转成时间字符串
            item.put("visitTime",DateUtil.formatDateTime((Date) item.get("visitTime")));
        });
        JSONObject params = new JSONObject();
        params.put("estateId","479125459456491520");
        params.put("records",list);
        String s = httpClientService.doPost(HOST + "/api/ai-voice/v1/visit/sync", params.toString(), getHeaderSignV1());
    }

    public static void main(String[] args) {
        visitSyncExcel();
//        visitSync();
//        visitSyncEs();
//        syncBatchExcel("syncBatch-241202.xlsx");
//        syncBatchExcel("syncBatchDeal-241202.xlsx");
    }

    private static void syncBatchExcel(String fileName) {
        ExcelReader staffReader = new ExcelReader("D:\\\\旺小宝同步到访\\"+fileName, 0);
        List<Map<String, Object>> list = staffReader.readAll();
        //把电话脱敏和顾问手机号转成字符串
        int successCount = 0, failCount = 0;
        for (Map<String, Object> info : list) {
            JSONObject params = new JSONObject();
            info.remove("agentTypeNo");
            params.set("estateId",wxbProjectMapping.get(info.remove("saleTeamId").toString()));
            //对手机号脱敏
            info.put("cusPhone", DesensitizedUtil.mobilePhone(info.get("cusPhone").toString()));
            if (info.containsKey("consultantPhone")) {
                info.put("consultantPhone",info.get("consultantPhone").toString());
            }
            //如果有标签推送
            List<JSONObject> tags = new ArrayList<>();
            for (WxbPushCustomerLabelEnum labelEnum : WxbPushCustomerLabelEnum.values()) {
                String value = (String) info.remove(labelEnum.getField());
                if (value != null) {
                    tags.add(JSONUtil.createObj().set("tagName",labelEnum.getLabelName()).set("tagValue",value));
                    info.putIfAbsent("tags",tags);
                }
            }
            //处理成交时间
            Date signingDate = (Date) info.remove("signingDate");
            if (signingDate != null) {
                info.put(dealDateAttrMap.get(Convert.toInt(info.get("dealStatus"))), DateUtil.formatDateTime(signingDate));
            }
            //处理初访时间
            Object firstVisitTime = info.remove("firstVisitTime");
            if (firstVisitTime instanceof Date) {
                info.put("firstVisitTime", DateUtil.formatDateTime((Date) firstVisitTime));
            }
            params.set("customers", ListUtil.of(info));
            try{
                String s = httpClientService.doPost(HOST + "/api/customer/v1/customer/sync-batch", params.toString(), getHeaderSignV1());
                JSONObject result = JSONUtil.parseObj(s);
                if (result.getJSONObject("data").getJSONArray("fails").size() > 0) {
                    System.out.println(s);
                    failCount++;
                } else {
                    successCount++;
                }
            } catch (Exception e) {
                e.printStackTrace();
                failCount++;
            }
        }
        System.out.println("成功："+successCount+" 失败："+failCount);
    }

    private static Map<String, String> getProjectIdMap() {
        ExcelReader staffReader = new ExcelReader("D:\\temp\\mapping.xlsx", 0);
        List<Map<String, Object>> staffList = staffReader.readAll();
        Map<String,String> map2 = new HashMap<>();
        map2.put("1000112","296184550369796096");
        map2.put("1001272","296122905077481472");
        return staffList.stream().collect(Collectors.toMap(item -> item.get("customer_opportunity_id").toString(), item -> map2.get(item.get("sale_team_id").toString())));
    }


    static Map<String,String> header = null;
    private static Map<String,String> getHeaderSignV1() {
        if (header != null) {
            return header;
        }
        String s = httpClientService.doGet(StrUtil.format(HOST + "/oauth/token?grant_type=client_credentials&client_id={}&client_secret={}",client_id,client_secret),null,null);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        String accessToken = jsonObject.getStr("access_token");
        header = new HashMap<>();
        header.put("Authorization", "Bearer " + accessToken);
        return header;
    }

}
